package com.gok.einvoice.web.controller.taxiRecognize;

import com.alibaba.fastjson2.JSONObject;
import com.gok.einvoice.common.annotation.Log;
import com.gok.einvoice.common.core.controller.BaseController;
import com.gok.einvoice.common.core.domain.AjaxResult;
import com.gok.einvoice.common.core.page.TableDataInfo;
import com.gok.einvoice.common.enums.BusinessType;
import com.gok.einvoice.common.exception.base.BaseException;
import com.gok.einvoice.common.utils.Base64Util;
import com.gok.einvoice.common.utils.HttpUtil;
import com.gok.einvoice.common.utils.poi.ExcelUtil;
import com.gok.einvoice.web.entity.TaxiInvoice;
import com.gok.einvoice.web.service.ITaxiInvoiceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/taxi")
@Api(tags = "出租车发票识别")
public class TaxiInvoiceController extends BaseController {

    @Autowired
    private ITaxiInvoiceService taxiInvoiceService;

    /**
     * 出租车票识别
     * @param file
     * @return
     */
    @PostMapping("/recognize")
    @ApiOperation(value = "出租车发票识别")
    public AjaxResult recognize(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new BaseException("文件错误");
        }

        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/taxi_receipt";
        String tokenUrl = "https://aip.baidubce.com/oauth/2.0/token";
        String tokenParam = "grant_type=client_credentials&client_id=hbTDfDcQGFPkOBZOGFDeUdt6&client_secret=yGcRbHWP5PMVAr6tOkQcpIRMaDztBD5z";

        try {
            // 读取文件内容并进行Base64编码
            byte[] imgData = file.getBytes();
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;

            //获取access_token
            String tokenObj = HttpUtil.post(
                    tokenUrl,
                    null,
                    tokenParam);
            JSONObject obj = JSONObject.parseObject(tokenObj);
            String accessToken = obj.get("access_token").toString();
            if (!StringUtils.hasText(accessToken)) {
                return AjaxResult.error("获取access_token失败");
            }

            //获取发票识别结果
            String result = HttpUtil.post(url, accessToken, param);
            JSONObject jsonResult = JSONObject.parseObject(result);
            if (jsonResult.get("error_code") != null) {
                return AjaxResult.error("出租车发票识别失败", jsonResult.get("error_msg").toString());
            }
            return AjaxResult.success(jsonResult);
        } catch (Exception e) {
            throw new BaseException("出租车发票识别失败");
        }
    }

    /**
     * 查询出租车发票列表
     */
    @PreAuthorize("@ss.hasPermi('taxiRecognize:invoice:list')")
    @GetMapping("/list")
    @ApiOperation("查询出租车发票列表")
    public TableDataInfo list(TaxiInvoice taxiInvoice)
    {
        startPage();
        List<TaxiInvoice> list = taxiInvoiceService.selectTaxiInvoiceList(taxiInvoice);
        return getDataTable(list);
    }

    /**
     * 导出出租车发票列表
     */
    @PreAuthorize("@ss.hasPermi('taxiRecognize:invoice:export')")
    @Log(title = "出租车发票", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出出租车发票列表")
    public void export(HttpServletResponse response, TaxiInvoice taxiInvoice)
    {
        List<TaxiInvoice> list = taxiInvoiceService.selectTaxiInvoiceList(taxiInvoice);
        ExcelUtil<TaxiInvoice> util = new ExcelUtil<TaxiInvoice>(TaxiInvoice.class);
        util.exportExcel(response, list, "出租车发票数据");
    }

    /**
     * 获取出租车发票详细信息
     */
    @PreAuthorize("@ss.hasPermi('taxiRecognize:invoice:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取出租车发票详细信息")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(taxiInvoiceService.selectTaxiInvoiceById(id));
    }

    /**
     * 新增出租车发票
     */
    @PreAuthorize("@ss.hasPermi('taxiRecognize:invoice:add')")
    @Log(title = "出租车发票", businessType = BusinessType.INSERT)
    @ApiOperation("新增出租车发票")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody TaxiInvoice taxiInvoice)
    {
        return toAjax(taxiInvoiceService.insertTaxiInvoice(taxiInvoice));
    }

    /**
     * 修改出租车发票
     */
    @PreAuthorize("@ss.hasPermi('taxiRecognize:invoice:edit')")
    @Log(title = "出租车发票", businessType = BusinessType.UPDATE)
    @ApiOperation("修改出租车发票")
    @PutMapping("/update")
    public AjaxResult edit(@RequestBody TaxiInvoice taxiInvoice)
    {
        return toAjax(taxiInvoiceService.updateTaxiInvoice(taxiInvoice));
    }

    /**
     * 删除出租车发票
     */
    @PreAuthorize("@ss.hasPermi('taxiRecognize:invoice:remove')")
    @Log(title = "出租车发票", businessType = BusinessType.DELETE)
    @ApiOperation("删除出租车发票")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(taxiInvoiceService.deleteTaxiInvoiceByIds(ids));
    }
}
